const Koa = require('koa')
const body = require('koa-body')
const staticServ = require('koa-static')
const path = require('path')
const views = require('koa-views')
const mongoose = require('mongoose')
const session = require('koa-session')

const conf = require('./conf')
mongoose.connect(conf.db)

const conn = mongoose.connection

conn.on('error', (err) => {
    throw err
})

conn.on('open', () => {
    console.log('数据库连接成功')
})

const app = new Koa()

app.use(body())
app.use(staticServ(path.join(__dirname, '/public')))
app.use(views(
    path.join(__dirname, '/views'),
    {
        extension: 'ejs'
    }
))

// 加 session 中间件
app.keys = [conf.app_keys]
const session_conf = {
    key: 'nodeBlog:key',
    maxAge: 1000 * 60 * 60 * 24 * 7, // cookie 7天过期
    autoCommit: true,
    overwrite: true,    // 是否可以覆盖
    httpOnly: true,     // 只有服务器才可以修改
    signed: true,       // 签名
    rolling: true,      // 强制在每个会话上标识 cookie
}
app.use(session(session_conf, app))

// 路由
const indexRouter = require('./routes/index')
const userRouter = require('./routes/user')
const articleRouter = require('./routes/article')

app.use(indexRouter.routes())
app.use(userRouter.routes())
app.use(articleRouter.routes())

app.listen(80, () => {
    console.log('server is runging')
})
